package com.right.health.app.hyphenate.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.platform.comapi.map.A;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hyphenate.easeui.ui.EaseChatFragment;
import com.hyphenate.util.EasyUtils;
import com.magics.http.listener.OnHttpListener;
import com.magics.http.model.Request;
import com.magics.http.model.Response;
import com.right.health.app.R;
import com.right.health.app.bean.ChatMemberInfo;
import com.right.health.app.greendao.DaoUtilsStore;
import com.right.health.app.net.ConsultApi;
import com.right.health.app.ui.main.MainActivity;
import com.vendor.social.utils.CollectionUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 单聊页面
 */
public class ChatActivity extends BaseActivity{

    public static final String BUNDLE_CHAT_ID_KEY = "userId";

    public static ChatActivity activityInstance;

    private EaseChatFragment chatFragment;

    String toChatUsername;

    private ConsultApi mApi;

    public static void launch(Context context,String id){
        Bundle bundle = new Bundle();
        bundle.putString(BUNDLE_CHAT_ID_KEY,id);
        Intent intent = new Intent(context, ChatActivity.class);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.em_activity_chat);
        activityInstance = this;
        //get user id or group id
        if(getIntent().getExtras() != null) {
            toChatUsername = getIntent().getExtras().getString(BUNDLE_CHAT_ID_KEY);
        }

        //use EaseChatFratFragment
        chatFragment = new ChatFragment();
        //pass parameters to chat fragment
        chatFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction().add(R.id.container, chatFragment).commit();
        if (!TextUtils.isEmpty(toChatUsername)&& CollectionUtil.isEmpty(DaoUtilsStore.getInstance().getChatMemberInfoDaoUtils().queryByNativeSql("where HXID = ?",new String[]{toChatUsername}))) {
            Log.i("TAG", "onCreate: refreshChatMemberInfo: "+toChatUsername);
            mApi = new ConsultApi();
            mApi.setListener(new OnHttpListener() {
                @Override
                public void onResponse(Request request, Response response) {
                    if (!response.isResponseFail()) {
                        try {
                            JSONObject jsonObject = new JSONObject(response.data);
                            String infoStr = jsonObject.optString("users");
                            List <ChatMemberInfo>list = new Gson().fromJson(infoStr, new TypeToken<List<ChatMemberInfo>>() {
                            }.getType());
                            if (!CollectionUtil.isEmpty(list)) {
                                DaoUtilsStore.getInstance().getChatMemberInfoDaoUtils().insert(list.get(0));
                                chatFragment.refresh(list.get(0).getRealname());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            List<String> list = new ArrayList<>();
            list.add(toChatUsername);
            mApi.getChatMemberInfo(list);
        }
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityInstance = null;
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }

    }
    
    @Override
    public void onBackPressed() {
        chatFragment.onBackPressed();
        if (EasyUtils.isSingleActivity(this)) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }
    }
    
    public String getToChatUsername(){
        return toChatUsername;
    }


}
